<?php

namespace App\Models;

use App\Http\Controllers\Controller;
use App\Http\Controllers\QrCodeController;
use App\Http\Controllers\Wechat\AppletAuthController;
use App\Http\Controllers\Wechat\ServiceController;
use Exception;
use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Support\Facades\Log;

/**
 * 用户微信小程序信息
 * Class ArticleTypeModel
 * @package app\common\model
 */
class UserAppletInfo extends BaseModel
{
    use HasFactory;

    const CREATED_AT = 'create_time';
    const UPDATED_AT = 'change_time';

    protected $table = 'user_applet_info';


    /**
     * 登录或修改微信信息
     * @param open_id open_id  openid作为主账号
     */
    public function change($data, $field = [], $findWhere = [])
    {
        $res = $this->where('open_id', $data['open_id'])->first();
        $is_insert_user_info = false;
        if (empty($res)) {
            $res = $this;
            $is_insert_user_info = true;

            //已经存在的不允许修改昵称
            $res->nickname = $data['nickname'];
            $res->head_img = $data['head_img'];
        }
        $res->union_id = $data['union_id'];
        $res->open_id = $data['open_id'];
        if (!empty($data['session_key'])) $res->session_key = $data['session_key']; //小程序增加
        $res->save();

        //写入用户信息
        $userInfoModel = new UserInfo();
        if ($is_insert_user_info) {
            $userInfoModel->token = get_guid();
            $userInfoModel->applet_id = $res->id;

            $user_serial_number = $userInfoModel->getUserRandomSerialNumber();
            if (empty($user_serial_number)) {
                throw new Exception('用户ID生成失败');
            }
            $userInfoModel->serial_number = $user_serial_number;

            $qrCodeObj = new QrCodeController();
            $qr_code = $qrCodeObj->getQrCode('user_info');
            $qr_url = $qrCodeObj->setQr($qr_code, true);

            $userInfoModel->qr_code = $qr_code;
            $userInfoModel->qr_url = $qr_url;

            $userInfoModel->save();

            $token =  $userInfoModel->token;
            $qr_code =  $userInfoModel->qr_code;
        } else {
            $user_info = $userInfoModel->getUserInfoByAppletId($res->id);
            $qr_code = $user_info['qr_code'];
            $token = $user_info['token'];
        }

        return ['is_add' => $is_insert_user_info, 'applet_id' => $res->id, 'token' => $token, 'qr_code' => $qr_code, 'nickname' => $res->nickname, 'head_img' => $res->head_img];
    }

    /**
     * 登录或修改微信信息
     * @param tel 用手机号码作为主账号
     */
    public function changeByTel($data)
    {
        $res = $this->where('tel', $data['tel'])->first();
        //  $res = $this->where('open_id', $data['open_id'])->first();//因为现在小程序绑定手机号时，和微信公众号一样的流程，所以每次如果绑定不同的手机号，则进行修改
        $is_insert_user_info = false;
        if (empty($res)) {
            $res = $this;
            $is_insert_user_info = true;

            //已经存在的不允许修改昵称
            $res->tel = $data['tel'];
            $res->nickname = $data['nickname'];
            $res->head_img = $data['head_img'];
            $res->open_id = $data['open_id'];
            $res->session_key = $data['session_key'];
            $res->union_id = $data['union_id'];
            $res->source_invite = $data['invite'];
        } elseif (empty($res['open_id'])) {
            //如果是退出登录需要删除以下信息
            $res->open_id = $data['open_id'];
            $res->session_key = $data['session_key'];
            $res->union_id = $data['union_id'];
            $res->nickname = $data['nickname'];
            $res->head_img = $data['head_img'];
        }
        $res->save();

        $userInfoModel = new UserInfo();
        //写入用户信息
        $user_info = $userInfoModel->where('tel', $data['tel'])->first();
        if (empty($user_info)) {
            $userInfoModel = new UserInfo();
            $userInfoModel->token = get_guid();
            $userInfoModel->applet_id = $res->id;

            $qrCodeObj = new QrCodeController();
            $qr_code = $qrCodeObj->getQrCode('user_info');
            // $qr_url = $qrCodeObj->setQr($qr_code, true);
            //生成用户推广二维码
            $appletObj = new AppletAuthController();
            $save_addr = 'qr/' . date('Y-m-d') . '/' . uniqid() . date('ymdhis') . '.png';
            $qr_url_res = $appletObj->getAppletQrCode($qr_code, public_path('uploads') . '/' . $save_addr);
            if ($qr_url_res) {
                $qr_url = $save_addr;
            } else {
                throw new Exception('用户二维码生成失败');
            }

            $userInfoModel->tel =  $data['tel'];
            $userInfoModel->qr_code = $qr_code;
            $userInfoModel->qr_url = $qr_url;
            $userInfoModel->nickname = $res->nickname;
            $userInfoModel->head_img = $res->head_img;

            $user_serial_number = $userInfoModel->getUserRandomSerialNumber();
            if (empty($user_serial_number)) {
                throw new Exception('用户ID生成失败');
            }
            $userInfoModel->serial_number = $user_serial_number;

            $userInfoModel->save();

            $user_info =  $userInfoModel;
        } elseif ($user_info && empty($user_info['applet_id'])) {
            $qrCodeObj = new QrCodeController();
            if (empty($user_info['qr_code'])) {
                $qr_code = $qrCodeObj->getQrCode('user_info');
                $user_info->qr_code = $qr_code;
            } else {
                $qr_code = $user_info['qr_code'];
            }
            if (empty($user_info['qr_url'])) {
                //生成用户推广二维码
                $appletObj = new AppletAuthController();
                $save_addr = 'qr/' . date('Y-m-d') . '/' . uniqid() . date('ymdhis') . '.png';
                $qr_url_res = $appletObj->getAppletQrCode($qr_code, public_path('uploads/') . $save_addr);
                if ($qr_url_res) {
                    $qr_url = $save_addr;
                } else {
                    throw new Exception('用户二维码生成失败');
                }
                $user_info->qr_url = $qr_url;
            }

            $user_info->applet_id = $res->id;
            $user_info->save();

            //把微信昵称和头像也改成用户表的昵称和头像
            $this->where('id', $res->id)->update(['nickname' => $user_info['nickname'], 'head_img' => $user_info['head_img']]);
        }
        return [
            'is_add' => $is_insert_user_info,
            'user_id' => $user_info['id'],
            'applet_id' => $res->id,
            'token' => $user_info['token'],
            'qr_code' => $user_info['qr_code'],
            'nickname' => $user_info['nickname'],
            'head_img' => $user_info['head_img'],
            'serial_number' => $user_info['serial_number']
        ];
    }


    /**
     * 获取用户open_id
     * @param $user_id
     */
    public static function getOpenIdByUserId($user_id)
    {
        $applet_id = UserInfo::where('id', $user_id)->value('applet_id');
        return self::where('id', $applet_id)->value('open_id');
    }

    /**
     * 根据applet_id 获取读微信信息
     */
    public function getWechatByAppletIds($applet_id_arr)
    {
        $res = $this->select('head_img', 'nickname')->whereIn('id', $applet_id_arr)->get();
        return $res;
    }
}
